package com.mini.common.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 小鱼儿
 * @date 2020/11/17 16:33
 */
public class JacksonUtil {
    private final static Logger logger = LoggerFactory.getLogger(JacksonUtil.class);
    private static ObjectMapper mapper = new ObjectMapper();


    public static String toJsonString(Object object) {
        String json = null;
        if (object != null) {
            try {
                json = mapper.writeValueAsString(object);
            } catch (JsonProcessingException e) {
                logger.info("json转换异常：" + e.getMessage(), e);
            }
        }
        return json;
    }

    public static <T> T stringToBean(String jsonStr, Class<T> cls) {
        T t = null;
        if (mapper != null) {
            mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
            mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            try {
                t = mapper.readValue(jsonStr, cls);
            } catch (JsonProcessingException e) {
                logger.info("stringToBean转换异常：" + e.getMessage(), e);
            }
        }
        return t;
    }

    public static <T> List<T> stringToList(String jsonStr, Class cls) {
        JavaType collectionType = getCollectionType(mapper, ArrayList.class, cls);
        List<T> retList = null;
        try {
            retList = mapper.readValue(jsonStr, collectionType);
        } catch (Exception e) {
            logger.info("stringToBean转换异常：" + e.getMessage(), e);
        }
        return retList;
    }

    public static JavaType getCollectionType(ObjectMapper mapper, Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }
}
